const state = {
  templates: [],
  currentTemplate: null,
  conversionResults: [],
  accuracy: 0
}

const mutations = {
  SET_TEMPLATES(state, templates) {
    state.templates = templates
  },
  SET_CURRENT_TEMPLATE(state, template) {
    state.currentTemplate = template
  },
  SET_CONVERSION_RESULTS(state, results) {
    state.conversionResults = results
    // 計算平均準確率
    if (results.length > 0) {
      const totalAccuracy = results.reduce((sum, result) => sum + result.accuracy, 0)
      state.accuracy = totalAccuracy / results.length
    }
  },
  SET_ACCURACY(state, accuracy) {
    state.accuracy = accuracy
  },
  ADD_TEMPLATE(state, template) {
    state.templates.push(template)
  },
  UPDATE_TEMPLATE(state, { id, updates }) {
    const index = state.templates.findIndex(t => t.id === id)
    if (index !== -1) {
      state.templates[index] = { ...state.templates[index], ...updates }
    }
  }
}

const actions = {
  async uploadTemplate({ commit }, template) {
    // 模擬API調用
    const newTemplate = {
      id: Date.now(),
      name: template.name,
      content: template.content,
      version: '1.0',
      uploadTime: new Date().toISOString(),
      status: 'pending'
    }
    commit('ADD_TEMPLATE', newTemplate)
    return newTemplate
  },
  
  async convertTemplate({ commit, state }, templateId) {
    // 模擬轉換過程
    const template = state.templates.find(t => t.id === templateId)
    if (template) {
      const result = await performConversion(template.content)
      commit('SET_CONVERSION_RESULTS', [...state.conversionResults, result])
      return result
    }
  }
}

const getters = {
  getTemplateById: (state) => (id) => {
    return state.templates.find(t => t.id === id)
  },
  getPendingTemplates: (state) => {
    return state.templates.filter(t => t.status === 'pending')
  },
  getConvertedTemplates: (state) => {
    return state.templates.filter(t => t.status === 'converted')
  }
}

// 模擬轉換邏輯
async function performConversion(content) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const result = {
        id: Date.now(),
        originalContent: content,
        structuredContent: {
          title: extractTitle(content),
          parties: extractParties(content),
          caseType: extractCaseType(content),
          claims: extractClaims(content),
          keyPoints: extractKeyPoints(content)
        },
        accuracy: Math.random() * 0.3 + 0.7, // 70%-100%的準確率
        conversionTime: new Date().toISOString()
      }
      resolve(result)
    }, 2000)
  })
}

function extractTitle(content) {
  // 簡單的標題提取邏輯
  const lines = content.split('\n')
  for (let line of lines) {
    if (line.includes('判決書') || line.includes('裁定書') || line.includes('調解書')) {
      return line.trim()
    }
  }
  return '未知標題'
}

function extractParties(content) {
  // 當事人信息提取
  const parties = []
  const lines = content.split('\n')
  for (let line of lines) {
    if (line.includes('原告') || line.includes('被告') || line.includes('上訴人') || line.includes('被上訴人')) {
      parties.push(line.trim())
    }
  }
  return parties
}

function extractCaseType(content) {
  // 案由提取
  const lines = content.split('\n')
  for (let line of lines) {
    if (line.includes('案由') || line.includes('糾紛')) {
      return line.trim()
    }
  }
  return '未知案由'
}

function extractClaims(content) {
  // 訴訟請求提取
  const claims = []
  const lines = content.split('\n')
  let inClaimsSection = false
  for (let line of lines) {
    if (line.includes('訴訟請求') || line.includes('請求')) {
      inClaimsSection = true
      continue
    }
    if (inClaimsSection && line.trim()) {
      claims.push(line.trim())
    }
  }
  return claims
}

function extractKeyPoints(content) {
  // 裁判要點提取
  const keyPoints = []
  const lines = content.split('\n')
  let inKeyPointsSection = false
  for (let line of lines) {
    if (line.includes('裁判要點') || line.includes('本院認為')) {
      inKeyPointsSection = true
      continue
    }
    if (inKeyPointsSection && line.trim()) {
      keyPoints.push(line.trim())
    }
  }
  return keyPoints
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}